package org.daidai.abstrusewriting.homepage.top;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.design.widget.AppBarLayout;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationManagerCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.RemoteViews;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.squareup.picasso.Picasso;

import org.daidai.abstrusewriting.R;
import org.daidai.abstrusewriting.homepage.top.model.TrackDetail;
import org.daidai.abstrusewriting.homepage.top.service.ImageAsyncTask;
import org.daidai.abstrusewriting.homepage.top.service.NotificationService;
import org.daidai.abstrusewriting.homepage.top.service.PlayBindService;
import org.daidai.abstrusewriting.homepage.top.service.TopService;

import java.text.SimpleDateFormat;

import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;
import rx.Observable;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class PlayActivity extends AppCompatActivity implements NotificationService, View.OnClickListener, Runnable, ServiceConnection, SeekBar.OnSeekBarChangeListener {

    private long trackId;
    private long trackUid;
    private ImageView poster;
    private TextView txtCurrentTime;
    private TextView txtTotalTime;
    private ImageView imageLogo;
    private TextView txtAlbumTitle;
    private TextView txtFollows;
    private TextView txtTitle;
    private TextView txtPlayTimes;
    private TextView txtCreateTime;
    private TextView txtIntro;
    private ImageView btnStart;
    private String playUrl32;
    private TrackDetail trackDetail = null;
    private boolean hasLocation;
    private boolean hasRegistered;
    private boolean isPlay;
    private AppBarLayout appBarLayout;
    private SeekBar seekBar;
    private long duration;
    private RemoteViews contentView;

    private PlayBindService.MyBinder myBinder;
    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case 998:
                    if (isPlay) {
                        btnStart.setImageResource(R.mipmap.player_toolbar_pause_normal);
                    } else {
                        btnStart.setImageResource(R.mipmap.player_toolbar_play_normal);
                    }
                    break;
                case 999:
                    int x = (int) msg.obj;
                    float alpha;
                    if (x >= 228) {
                        alpha = 1 - (float) ((x - 228) / 882.0);
                    } else {
                        alpha = 1.0f;
                    }
                   appBarLayout.setAlpha(alpha);
                    break;
                case 1000:
                    if (myBinder != null) {
                        long currentTime = myBinder.getCurrentTime();
                        String s = transTime(((int) currentTime / 1000));
                        txtCurrentTime.setText(s);
                        long duration = myBinder.getDuration();
                    }
                    break;
            }
            return false;
        }
    });
    private long currentPosition;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_play);

        Log.d("PlayActivity", "onCreate: " + this);

        Toolbar toolbar = (Toolbar) findViewById(R.id.playing_tool_bar);
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
        appBarLayout = (AppBarLayout) findViewById(R.id.playing_app_bar);
        appBarLayout.setAlpha(0.0f);
        hasLocation = true;

        seekBar = (SeekBar) findViewById(R.id.music_seek_bar);
        seekBar.setOnSeekBarChangeListener(this);

        trackId = 0;
        trackUid = 0;
        if (getIntent() != null) {
            trackId = getIntent().getLongExtra("trackId", 0);
            trackUid = getIntent().getLongExtra("uid", 0);
        }

        initView();
        getData();

        Thread thread = new Thread(this);
        thread.start();

    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    public void getData() {
        Retrofit.Builder builder = new Retrofit.Builder();
        Retrofit retrofit = builder.baseUrl("http://mobile.ximalaya.com/v1/track/")
                .addCallAdapterFactory(RxJavaCallAdapterFactory.createWithScheduler(Schedulers.io()))
                .addConverterFactory(ScalarsConverterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        Log.d("PlayActivity", "trackId: " + trackId + "   trackUid:" + trackUid);
        if (trackId != 0 && trackUid != 0) {
            Observable<TrackDetail> observable = retrofit.create(TopService.class).getTrackDetail("android", trackId, trackUid);
            observable.observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<TrackDetail>() {

                        @Override
                        public void onCompleted() {

                        }

                        @Override
                        public void onError(Throwable e) {
                            Log.d("PlayActivity", "onError: ");
                            Toast.makeText(PlayActivity.this, "网络请求错误", Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void onNext(TrackDetail s) {
                            trackDetail = s;
                            Log.d("PlayActivity", "onNext: " + s.toString());
                            Picasso.with(PlayActivity.this).load(s.getCoverLarge()).into(poster);
                            txtTotalTime.setText(transTime(((int) s.getDuration())));
                            duration = s.getDuration();
                            Picasso.with(PlayActivity.this).load(s.getAlbumImage()).into(imageLogo);
                            txtAlbumTitle.setText(s.getAlbumTitle());
                            txtFollows.setText(s.getUserInfo().getFollowers() + "人订阅");
                            txtTitle.setText(s.getTitle());
                            txtPlayTimes.setText(Integer.toString(s.getPlaytimes()) + "次播放");
                            txtIntro.setText(s.getIntro());
                            txtCreateTime.setText(transDate(s.getCreatedAt()));
                            playUrl32 = s.getPlayUrl32();


                            contentView = new RemoteViews(getPackageName(),
                                    R.layout.notification_item);
                            contentView.setTextViewText(R.id.no_title, s.getTitle());
                            contentView.setTextViewText(R.id.no_name, s.getUserInfo().getNickname());
                            ImageAsyncTask task = new ImageAsyncTask();
                            task.setService(PlayActivity.this);
                            task.execute(s.getCoverSmall());
                        }
                    });
        }
    }

    public void initView() {
        poster = (ImageView) findViewById(R.id.playing_poster);
        txtCurrentTime = (TextView) findViewById(R.id.playing_current_time);
        txtCurrentTime.setText("00:00");
        txtTotalTime = (TextView) findViewById(R.id.playing_total_time);
        txtTotalTime.setText("00:00");
        ImageView imageList = (ImageView) findViewById(R.id.playing_list);
        ImageView imagePrevious = (ImageView) findViewById(R.id.playing_previous);
        ImageView imageNext = (ImageView) findViewById(R.id.playing_next);
        ImageView imaegTimer = (ImageView) findViewById(R.id.playing_timer);
        imageLogo = (ImageView) findViewById(R.id.playing_author);
        txtAlbumTitle = (TextView) findViewById(R.id.playing_album_Title);
        txtFollows = (TextView) findViewById(R.id.playing_user_following);
        txtTitle = (TextView) findViewById(R.id.playing_title);
        txtPlayTimes = (TextView) findViewById(R.id.playing_play_times);
        txtCreateTime = (TextView) findViewById(R.id.playing_createdAt);
        txtIntro = (TextView) findViewById(R.id.playing_intro);
        btnStart = (ImageView) findViewById(R.id.playing_start);
        btnStart.setOnClickListener(this);
    }

    public String transTime(int time) {
        String ret = null;
        int seconds = time % 60;
        int minites = (time - seconds) / 60;
        ret = String.format("%02d", minites) + ":" + String.format("%02d", seconds);
        return ret;
    }

    public String transDate(long date) {
        String ret = null;
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        ret = format.format(date);
        return ret;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.playing_start:
                Log.d("Play", "onClick: " + isPlay);
                Message message = handler.obtainMessage(998);
                handler.sendMessage(message);

//                setNotification();
                Intent intent = new Intent(this, PlayBindService.class);
                if (isPlay) {
                    if (myBinder != null) {
                        myBinder.stop();
                    }
                } else {
                    intent.putExtra("url", playUrl32);
                    if (myBinder != null) {
                        myBinder.start();
                    }
                }

                startService(intent);
                hasRegistered = true;
                bindService(intent, this, BIND_AUTO_CREATE);

                isPlay = !isPlay;

                Thread thread = new Thread(new Runnable() {
                    @Override
                    public void run() {

                        while (isPlay) {

                            Message msg = handler.obtainMessage(1000);
                            handler.sendMessage(msg);

                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                });
                thread.start();

                NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
                builder.setContentTitle("通知")
                        .setContent(contentView)
                        .setSmallIcon(R.mipmap.ic_launcher);

                builder.setDefaults(Notification.DEFAULT_ALL);
                Intent in = new Intent(this, PlayActivity.class);

                if (trackDetail != null) {

                    in.putExtra("uid", trackUid);
                    in.putExtra("trackId", trackId);
                }
                in.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                PendingIntent pi =
                        PendingIntent.getActivity(this, 0, in, PendingIntent.FLAG_UPDATE_CURRENT);
                builder.setContentIntent(pi);
                builder.setOngoing(true);

                Notification n = builder.build();
                n.tickerText = "这是我自己的通知";
                NotificationManagerCompat manager = NotificationManagerCompat.from(this);
                manager.notify(998, n);

                break;
        }
    }

    @Override
    public void run() {
        //228   1110
        while (hasLocation) {
            int[] location = new int[2];
            txtCurrentTime.getLocationOnScreen(location);
            Message message = handler.obtainMessage(999);
            message.obj = location[1];
            handler.sendMessage(message);
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.playing_share, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                super.onBackPressed();
                break;
            case R.id.playing_share:
                //TODO:第三方分享

                ShareSDK.initSDK(this);
                OnekeyShare oks = new OnekeyShare();
                //关闭sso授权
                oks.disableSSOWhenAuthorize();

//                if (true == false) {
                if (trackDetail != null) {
                    oks.setTitle(trackDetail.getTitle());
                    oks.setText(trackDetail.getTitle() + "\n" + trackDetail.getIntro());
                    oks.setUrl(trackDetail.getTitle() + "\n" + trackDetail.getIntro() + trackDetail.getPlayUrl32());
//                    oks.setImageUrl(trackDetail.getCoverSmall());
                } else {
                    // 分享时Notification的图标和文字  2.5.9以后的版本不调用此方法
                    //oks.setNotification(R.drawable.ic_launcher, getString(R.string.app_name));
                    // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
                    oks.setTitle("标题");
                    // titleUrl是标题的网络链接，仅在人人网和QQ空间使用
                    oks.setTitleUrl("http://sharesdk.cn");
                    // text是分享文本，所有平台都需要这个字段
                    oks.setText("我是分享文本");
                    //分享网络图片，新浪微博分享网络图片需要通过审核后申请高级写入接口，否则请注释掉测试新浪微博
                    oks.setImageUrl("http://f1.sharesdk.cn/imgs/2014/02/26/owWpLZo_638x960.jpg");
                    // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
                    //oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
                    // url仅在微信（包括好友和朋友圈）中使用
                    oks.setUrl("http://sharesdk.cn");
                }

                // comment是我对这条分享的评论，仅在人人网和QQ空间使用
                oks.setComment("我是测试评论文本");
                // site是分享此内容的网站名称，仅在QQ空间使用
                oks.setSite("ShareSDK");
                // siteUrl是分享此内容的网站地址，仅在QQ空间使用
                oks.setSiteUrl("http://sharesdk.cn");
                // 启动分享GUI
                oks.show(this);
                break;
            case R.id.playing_help:
                //TODO：测试DialogLayout
                DialogFragment dialogFragment = new DialogFragment();

                break;
        }
        return true;
    }


    @Override
    protected void onDestroy() {
        hasLocation = false;
        if (hasRegistered) {
            unbindService(this);
        }

        super.onDestroy();
    }

    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        myBinder = (PlayBindService.MyBinder) service;
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        myBinder = null;
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        if (isPlay) {
            if (duration != 0) {
                currentPosition = ((long) ((progress * myBinder.getDuration()) / 100.0));
            }
        }
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        if (currentPosition != 0) {
            if (myBinder != null) {
                myBinder.setPosition(((int) currentPosition));
            }
        }
    }

    @Override
    public void send(Bitmap bitmap) {
        contentView.setImageViewBitmap(R.id.no_iv, bitmap);
    }
}
